package com.kalvan.admin.system.controller;


import com.github.pagehelper.Page;
import com.kalvan.admin.system.service.AuthService;
import com.kalvan.admin.system.service.RoleService;
import com.kalvan.commons.constant.LogGroup;
import com.kalvan.commons.db.system.mapper.MenuMapper;
import com.kalvan.commons.db.system.mapper.RoleMenuMapper;
import com.kalvan.commons.db.system.model.Menu;
import com.kalvan.commons.db.system.model.Role;
import com.kalvan.commons.db.system.model.RoleMenu;
import com.kalvan.commons.dto.system.RoleImport;
import com.kalvan.core.exception.BizException;
import com.kalvan.core.mybatis.PageInfo;
import com.kalvan.core.utils.BeanUtils;
import com.kalvan.core.valid.Add;
import com.kalvan.core.valid.Edit;
import com.kalvan.web.controller.BaseController;
import com.kalvan.web.exception.AdminReturnCode;
import com.kalvan.web.i18n.annotation.I18n;
import com.kalvan.web.log.annotation.SysLog;
import com.kalvan.web.servlet.annotation.Permission;
import com.kalvan.web.servlet.response.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色Controller
 *
 * @author kalvan
 * @date 2019-06-01 02:29:27
 */
@I18n("i18n/com/kalvan/admin/system/role")
@SysLog(group = LogGroup.ROLE)
@Api(tags = {"角色"})
@ApiIgnore
@RestController
@RequestMapping("system/role")
@Slf4j
public class RoleController extends BaseController {
    @Resource
    private RoleService roleService;
    @Resource
    private AuthService authService;
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private MenuMapper menuMapper;

    /**
     * 分页查询
     *
     * @param params 查询参数
     * @return R
     */
    @ApiOperation("分页查询")
    @PostMapping("list")
    @Permission("admin:system:role:list")
    public R list(PageInfo pageInfo, @RequestParam Map<String, String> params) {
        Page data = roleService.queryPage(pageInfo, params);
        return R.ok().putPage(data);
    }

    /**
     * 根据主键查询详情
     *
     * @param id 主键
     * @return R
     */
    @ApiOperation("主键查询")
    @GetMapping("info/{id}")
    @Permission("admin:system:role:info")
    public R info(@PathVariable("id") Long id) {
        Role role = roleService.findById(id);
        if (role == null) {
            throw new BizException(AdminReturnCode.REQUEST_ILLEGAL);
        }
        return R.ok().putData(role);
    }

    /**
     * 新增角色
     *
     * @param roleImport roleImport
     * @return R
     */
    @SysLog(remark = "新增角色")
    @ApiOperation("新增角色")
    @PostMapping("add")
    @Permission("admin:system:role:add")
    public R add(@Validated({Add.class}) RoleImport roleImport) {
        roleService.add(BeanUtils.newAndCopy(roleImport, Role.class));
        return R.ok();
    }

    /**
     * 修改角色
     *
     * @param roleImport roleImport
     * @return R
     */
    @SysLog(remark = "修改角色")
    @ApiOperation("修改角色")
    @PostMapping("edit")
    @Permission("admin:system:role:edit")
    public R edit(@Validated({Edit.class}) RoleImport roleImport) {
        if (roleImport.getId() == null) {
            return R.error(AdminReturnCode.REQUEST_ILLEGAL.getMsg());
        }
        roleService.edit(BeanUtils.newAndCopy(roleImport, Role.class));
        return R.ok();
    }

    /**
     * 根据主键删除角色
     *
     * @param ids ids
     * @return R
     */
    @SysLog(remark = "删除角色")
    @ApiOperation("删除角色")
    @PostMapping("delete")
    @Permission("admin:system:role:delete")
    public R delete(Long[] ids) {
        if (ArrayUtils.isEmpty(ids)) {
            return R.error(AdminReturnCode.REQUEST_ILLEGAL.getMsg());
        }
        int num = roleService.deleteBatch(ids);
        return R.ok(String.format("成功删除%s行数据", num));
    }

    @ApiOperation("获取角色权限树")
    @PostMapping("menuList")
    @Permission("admin:system:role:grant")
    public R menuList(Long id) {
        List<Menu> roleMenu = menuMapper.selectAllMenuByRoleId(id);
        List<Menu> menuList = authService.selectMenuList();
        return R.ok().putData(roleMenu).put("menuList", menuList);
    }

    @SysLog(remark = "角色授权")
    @ApiOperation("角色授权")
    @PostMapping("grant")
    @Permission("admin:system:role:grant")
    public R grant(Long roleId, Long[] menuIds) {
        if (roleId == null) {
            return R.error(AdminReturnCode.REQUEST_ILLEGAL.getMsg());
        }
        int num = roleService.grant(roleId, menuIds);
        return R.ok();
    }

    @ApiOperation("获取所有角色")
    @GetMapping("allRole")
    public R allRole() {
        return R.ok().putData(roleService.findAll());
    }

    @SysLog(remark = "角色复制")
    @ApiOperation("角色复制")
    @PostMapping("copy")
    @Permission("admin:system:role:grant")
    public R copy(Long roleId, Long copyRoleId) {
        if (roleId == null) {
            return R.error(AdminReturnCode.REQUEST_ILLEGAL.getMsg());
        }
        RoleMenu query = new RoleMenu();
        query.setRoleId(copyRoleId);
        List<RoleMenu> list = roleMenuMapper.select(query);
        if (!list.isEmpty()) {
            List<Long> menuIds = list.stream().map(e -> e.getMenuId()).collect(Collectors.toList());
            Long[] longs = new Long[menuIds.size()];
            int num = roleService.grant(roleId, menuIds.toArray(longs));
        }
        return R.ok();
    }
}
